<?
session_start();

$fileSuccess = false; 
$fileFail = false;
$captionFail= false;
$invalidFile = false;
$dateTrue = false;
$dateFalse = false;
$filenameFail = false;
$albumSelect = false;


require("../../mysql.config.inc");

$mysqli = new mysqli($host,$username,$password,$db);  

if (isset($_FILES['newphoto']) && isset($_POST['albumsIn'])) {

	if ($_FILES['newphoto']['error'] == 0) {
	
		if($_FILES['newphoto']['type'] == "image/jpeg"){
			$fileName = $_FILES['newphoto']['name'];
			
			if(preg_match("|[a-zA-Z0-9\s]|", $fileName)){
			
				move_uploaded_file($_FILES['newphoto']['tmp_name'], "../images/".$_FILES['newphoto']['name']);
				$fileSuccess = true;
				
				$img = imagecreatefromjpeg("../images/".$_FILES['newphoto']['name']);
				$width = imagesx($img);
				$height = imagesy($img);

				$thumb_width = 200;

				$new_width = $thumb_width;
				$new_height = floor($height * ($thumb_width/$width));

				$new_img = imagecreatetruecolor($new_width, $new_height);

				imagecopyresampled($new_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

				$return = imagejpeg($new_img, "../thumbs/images/".$_FILES['newphoto']['name']);

				imageDestroy($img);
				imageDestroy($new_img);
				
			}else{
				$filenameFail = true;
			}			
		}else{
			$invalidFile = true;
		}
	}else{
		$fileFail = true;
	}
	
	if($fileSuccess){
		
		if(isset($_POST['dateTaken']) && preg_match("|^[0-9]{4}[-]{1}[0-3]{1}[0-9]{1}[-]{1}[0-1]{1}[0-9]{1}|",$_POST['dateTaken'])){
			$dateTrue = true;
			$date = "'".$_POST['dateTaken']."'";
		}else{
			$dateFalse = true;
		}
		
		if(preg_match("|^[a-zA-Z0-9.,'\s]+$|", $_POST['caption']) && isset($_POST['albumsIn'])){
			$caption = $_POST['caption'];
			
			if($dateTrue){
				$query = ("INSERT INTO Photos (pid,Link,date_taken,Caption) 
				VALUES(NULL,\"images/$fileName\",$date,\"$caption\")");
			}else{
				$query = ("INSERT INTO Photos (pid,Link,date_taken,Caption) 
				VALUES(NULL,\"images/$fileName\",NOW(),\"$caption\")");
			}
			
			$mysqli->query($query);
			$newPid = $mysqli->query("SELECT MAX(pid) FROM Photos");
			
			$newPidArray = $newPid->fetch_array();
		
			$inAlbumArray = $_POST['albumsIn'];
			foreach($inAlbumArray as $aid){
				$albumCountResult = $mysqli->query("SELECT COUNT(aid) FROM AlbumIn WHERE aid = $aid");
				$albumCount = $albumCountResult->fetch_array();
				$sequenceNum = $albumCount[0] + 1;
				
				
				$albumsInQuery = "INSERT INTO AlbumIn (aid,pid,sequence) VALUES('$aid','$newPidArray[0]','$sequenceNum')";
				$mysqli->query($albumsInQuery);
				
			}
				
		}elseif(!preg_match("|^[a-zA-Z0-9.,'\s]+$|", $_POST['caption'])){
			$captionFail = true;
		}		
	}	
}elseif(isset($_FILES['newphoto']) && !isset($_POST['albumsIn'])){
	$albumSelect = true;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>A Photo Gallery</title>
	<link rel="stylesheet" type="text/css" href="../stylesheets/styles.css"/>
</head>

<body>

<div id="content">
	
	<div id="nav">
		<dl class="menu">
			<dd><a href="../index.php">Home</a></dd>
			<dd><a href="../albums.php">Albums</a></dd>
			<dd><a href="../photos.php">All Photos</a></dd>
			<dd class = "active"><a href="../admin.php">Administration</a></dd>
		</dl>
	</div>
	
	<h2>Administration: Upload a File</h2>
	
	<?if(!isset($_SESSION['logged_user'])){?>
	
		<div id="bodyText">
		You need to be Logged in to view this page, although it's curious how you got here in the first
		place.<br/>
		<a href="../admin.php">Log in</a>
		
	<?}else{?>
	
		<div id="bodyText">
		Please select a new picture to upload.<br/><br/>
		
		<?
		if($fileSuccess){
			print("<span class=\"alert\">The file ".$_FILES['newphoto']['name']." was uploaded successfully.</span><br/>\n");
		}elseif($fileFail){
			print"<span class=\"alert\">The file was not uploaded successfully.</span><br/>\n";
		}elseif($invalidFile){
			print"<span class=\"alert\">You may only upload a .jpg</span><br/>\n";
		}elseif($filenameFail){
			print("<span class=\"alert\">You will need to rename the file before you can upload it. Only letters
			and numbers are allowed. Security reasons. </span><br/>\n");
		}elseif($albumSelect){
			print("<span class=\"alert\">You need to select an Album for the photo to be in. Please try again, or make a new
			album if the ones here do not fit your taste.</span><br/>\n");
		}
		?>
		
		<form action="fileupload.php" method="post" name="upload" enctype="multipart/form-data">
			<p>
			Choose the file:<br/>
			<input type="file" id="chooseFile" name="newphoto"/><br/><br/>
			
			When was this photo taken? (YYYY-MM-DD)<br/>
			<input type="text" name="dateTaken"/><br/><br/>
			
			Now choose which albums this photo will be a part of:<br/>
			
			<?
				$albumList = $mysqli->query('SELECT* FROM Albums ORDER BY Title');
				while($dropList = $albumList->fetch_assoc()){
					print("<input type=\"checkbox\" name=\"albumsIn[]\" value=\"".$dropList['aid']."\"/>".$dropList['Title']."<br/>\n");
				}
			?>
			
			<br/>
			Enter a caption for the photo:<br/>
			<textarea rows="3" cols="50" name="caption">Put caption here</textarea><br/><br/>
			<input type="submit" name="uploadPhoto" value="Upload Photo"/>
			</p>	
		</form>
	
		<form action="../admin.php" method="post" name="logout">
			<p>
			<input type="hidden" name="logout"/>
			<input type="submit" value="Log Out"/>
			</p>
		</form>
		
	<?}
	$mysqli->close();
	?>
	</div>

</div>
</body>
</html>